import { Button, DatePicker } from "antd";
import { SendOutlined } from "@ant-design/icons";
import { memo, useEffect, useState } from "react";
import {
  Message,
  Modal,
  Notification,
  Select,
  Table,
  Button as ArcoButton,
} from "@arco-design/web-react";
import { CheckModificationWrapper, TableWrapper } from "./style";
import { useAppDispatch, useAppSelector } from "../../../../store";
import dayjs from "dayjs";
import { fetchUpdateExaminationAction } from "../../../../store/modules/patient";
interface CheckModificationProps {
  userId: number;
  getDataFn: (params: { userId: number }) => void;
}
const CheckModification = ({ userId, getDataFn }: CheckModificationProps) => {
  const [visible, setVisible] = useState(false);
  const [examination, setExamination] = useState<
    {
      key: number | null;
      examinationId: number | null;
      state: string | null;
      timeOn: string | null;
      name: string | null;
    }[]
  >([]);
  const dispatch = useAppDispatch();
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const { examinationList, modificationAndTaskList } = useAppSelector(
    (state) => state.patient
  );

  const toggleModal = (target: boolean) => {
    if (target && getDataFn && userId) {
      getDataFn({ userId }); // 在打开模态框时调用 onOpen 并传递 userId
    }
    setVisible(target);
  };
  useEffect(() => {
    if (modificationAndTaskList) {
      const currentExaminations = modificationAndTaskList?.examinationsVO?.map(
        (item: any) => {
          return {
            key: item.id,
            name: item.name,
            state: item.state,
            timeOn: item.timeOn,
            examinationId: item.examinationId,
          };
        }
      );
      setExamination(currentExaminations);
    }
  }, [modificationAndTaskList]);
  //?把修改的数组赋值给data
  const nowData = examination?.filter((item) => {
    return item.state === "0" || item.state === null;
  });
  // console.log(examination);
  const pastData = examination?.filter((item) => {
    return item.state !== "0" && item.state !== "null";
  });
  /**
   * @修改下拉列表函数
   * @param index
   * @param value
   */
  const handleExaminationChange = (index: number, value: number) => {
    // const
    // console.log(index, value);
    const matchItem = examinationList.find((item) => {
      return item.id === value;
    });
    setExamination((prev) => {
      const newExaminationList = [...prev];
      newExaminationList[index] = {
        ...newExaminationList[index],
        examinationId: value,
        state: matchItem ? matchItem.state : null,
      };
      return newExaminationList;
    });
  };

  /**
   * @修改时间
   * @param index
   * @param value
   */
  const handleDateChange = (index: number, value: string) => {
    // console.log(value);
    setExamination((prev) => {
      const newExaminationList = [...prev];
      newExaminationList[index] = {
        ...newExaminationList[index],
        timeOn: value,
      };
      return newExaminationList;
    });
  };

  /**
   * @新增按钮
   */
  const newAddExamination = () => {
    try {
      setExamination((prev) => [
        ...prev,
        {
          key: Date.now(),
          examinationId: null,
          state: null,
          timeOn: null,
          name: null,
        },
      ]);
    } catch (err) {
      Message.error("新增按钮失败");
    }
  };

  /**
   * @删除按钮
   */

  const deleteSelection = () => {
    if (selectedRowKeys.length === 0) {
      Message.warning("请先选择要删除的项");
      return;
    }
    const id = `${Date.now()}`;
    Notification.error({
      id,
      title: "警告",
      content: "确定要删除这条数据吗",
      btn: (
        <span>
          <ArcoButton
            type="secondary"
            size="small"
            onClick={() => {
              Notification.remove(id);
              setSelectedRowKeys([]);
            }}
            style={{ margin: "0 12px" }}
          >
            取消
          </ArcoButton>
          <ArcoButton
            type="primary"
            size="small"
            onClick={() => {
              setExamination((prev) =>
                prev.filter((item) => !selectedRowKeys.includes(item.key))
              );
              setSelectedRowKeys([]);
              // Message.success("删除成功");
              Notification.remove(id);
              Message.info("点击完以后再点击确认按钮即可删除");
            }}
          >
            确认
          </ArcoButton>
        </span>
      ),
    });
  };
  /**
   * @单选框列表
   */
  const onSelectChange = (newSelectedRowKeys: any) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    checkAll: false,
    onChange: onSelectChange,
  };

  /**
   * @更新检查
   */
  const handleSubmitExamination = async () => {
    const body = {
      userId,
      examinationList: examination.map((item) => {
        return {
          state: item.state || null,
          timeOn: item.timeOn || null,
          id: item.examinationId || null,
        };
      }),
      examinationListUpdate: [],
    };
    await dispatch(fetchUpdateExaminationAction(body));
    toggleModal(false);
  };
  const pastColums = [
    {
      title: "检查项目",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render: (value: string, record: any, index: number) => {
        if (value === "0") return <span>未开始</span>;
        if (value === "1") return <span>已完成</span>;
        if (value === "2") return <span>已逾期</span>;
      },
    },
    {
      title: "时间",
      dataIndex: "timeOn",
      key: "timeOn",
      render: (time: string, record: any, index: number) => {
        return (
          <DatePicker
            disabled
            placeholder="选择开始日期"
            value={time ? dayjs(time) : null}
            onChange={(_, newValue) =>
              handleDateChange(index, newValue as string)
            }
          />
        );
      },
    },
  ];
  const nowColums = [
    {
      title: "检查项目",
      dataIndex: "name",
      key: "name",
      render: (value: number, record: any, index: number) => {
        // console.log(record);

        return (
          <Select
            placeholder="请选择检查项目"
            value={record.examinationId || null}
            onChange={(newValue) => handleExaminationChange(index, newValue)}
          >
            {examinationList.map((item: any) => {
              return (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render: (value: string, record: any, index: number) => {
        if (value === "0") return <span>未开始</span>;
        if (value === "1") return <span>已完成</span>;
        if (value === "3") return <span>已逾期</span>;
      },
    },
    {
      title: "时间",
      dataIndex: "timeOn",
      key: "timeOn",
      render: (time: string, record: any, index: number) => {
        return (
          <DatePicker
            placeholder="选择开始日期"
            value={time ? dayjs(time) : null}
            onChange={(_, newValue) =>
              handleDateChange(index, newValue as string)
            }
          />
        );
      },
    },
  ];

  return (
    <CheckModificationWrapper>
      <Button
        icon={<SendOutlined />}
        size="small"
        type="link"
        style={{ gap: "2px" }}
        onClick={() => toggleModal(true)}
      >
        检查修改
      </Button>
      <Modal
        style={{ width: "650px" }}
        title="检查修改"
        visible={visible}
        onOk={() => toggleModal(false)}
        onCancel={() => toggleModal(false)}
        autoFocus={false}
        focusLock={true}
        footer={
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: "10px",
            }}
          >
            <Button key="newAdd" onClick={newAddExamination}>
              新增
            </Button>
            <Button key="delete" onClick={deleteSelection}>
              删除选中
            </Button>
            <Button key="cancel" onClick={() => setVisible(false)}>
              取消
            </Button>
            <Button type="primary" key="sure" onClick={handleSubmitExamination}>
              确定
            </Button>
          </div>
        }
      >
        <TableWrapper>
          <Table
            columns={pastColums}
            data={pastData}
            pagination={false}
            style={{ userSelect: "none", height: "250px", overflowY: "auto" }}
          />
          <Table
            rowSelection={rowSelection}
            columns={nowColums}
            data={nowData}
            style={{ userSelect: "none", height: "240px", overflowY: "auto" }}
            pagination={false}
          />
        </TableWrapper>
      </Modal>
    </CheckModificationWrapper>
  );
};
export default memo(CheckModification);
